package com.cz.modules.cll.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cz.common.utils.HikvisionApiUtil;
import com.cz.modules.cll.entity.CllMonitoringPointEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cz.common.utils.PageUtils;
import com.cz.common.utils.Query;

import com.cz.modules.cll.dao.CllVehicleRecordDao;
import com.cz.modules.cll.entity.CllVehicleRecordEntity;
import com.cz.modules.cll.service.CllVehicleRecordService;


@Service("cllVehicleRecordService")
public class CllVehicleRecordServiceImpl extends ServiceImpl<CllVehicleRecordDao, CllVehicleRecordEntity> implements CllVehicleRecordService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String startTime = (String)params.get("startTime");
        String endTime = (String)params.get("endTime");
        String monitoringId = (String)params.get("monitoringId");
        String plateNo = (String)params.get("plateNo");
        String vehicleType = (String)params.get("vehicleType");
    IPage<CllVehicleRecordEntity> page = this.page(
            new Query<CllVehicleRecordEntity>().getPage(params),
            new QueryWrapper<CllVehicleRecordEntity>()
                    .like(StringUtils.isNotBlank(plateNo),"plate_no",plateNo)
                    .ge(StringUtils.isNotBlank(startTime),"cross_time",startTime)
                    .le(StringUtils.isNotBlank(endTime),"cross_time",endTime)
                    .eq(StringUtils.isNotBlank(monitoringId),"monitoring_id",monitoringId)
                    .eq(StringUtils.isNotBlank(vehicleType),"vehicle_type",vehicleType)
                    .orderByDesc("cross_time")
    );
        return new PageUtils(page);
}
   /* @Override
    public List<CllVehicleRecordEntity> carflow(String type,String time, String monitoringIid) {
        List<CllVehicleRecordEntity> list=new ArrayList<>();
        Date date=new Date();
        List<String> timelist=new ArrayList<>();
        String beginTime="";
        String endTime="";
        if(!"".equals(time) || time !=null) {//前端自定义时间 按此时间查询
            if("24".equals(type)){//当天的数据
                beginTime =time+" 00:00:00";
                endTime =time+" 23:59:59";
                Date da=DateUtil.parse(endTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(da);


            }else if("30".equals(type)){//当月的数据
                beginTime =time+"-01 00:00:00";
                Date dd=DateUtil.parse(beginTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dd);
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 0);
                int day=calendar.get(Calendar.DAY_OF_MONTH);
                endTime = DateUtil.format(calendar.getTime(),"yyyy-MM-dd");
                endTime +=" 00:00:00";
                for (int i = 0; i < day; i++) {
                    calendar.add(Calendar.DAY_OF_MONTH, -i);//i天前
                    timelist.add(DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss"));
                }
            }
        }else{//未自定义时间
            if("24".equals(type)){//当天的数据
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.HOUR_OF_DAY, 1);//1小时后
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                int hour=calendar.get(Calendar.HOUR_OF_DAY);
                endTime=DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss");
                beginTime=DateUtil.format(date,"yyyy-MM-dd");
                beginTime +=" 00:00:00";
                for (int i = 0; i <hour ; i++) {
                    calendar.add(Calendar.HOUR_OF_DAY, -1);//1小时前
                    timelist.add(DateUtil.format(calendar.getTime(),"yyyy-MM-dd HH:mm:ss"));
                }
            }else if("30".equals(type)){//当月的数据
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                // 获取前月的第一天
                calendar.add(Calendar.MONTH, 0);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                beginTime= DateUtil.format(calendar.getTime(),"yyyy-MM-dd");
                beginTime +=" 00:00:00";
                // 获取当前月的最后一天
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(date);
                calendar1.add(Calendar.MONTH, 1);
                calendar1.set(Calendar.DAY_OF_MONTH, 0);
                int day=calendar.get(Calendar.DAY_OF_MONTH);
                endTime = DateUtil.format(calendar1.getTime(),"yyyy-MM-dd");
                endTime +=" 00:00:00";
                for (int i = 0; i < day; i++) {
                    calendar1.add(Calendar.DAY_OF_MONTH, -i);//i天前
                    timelist.add(DateUtil.format(calendar1.getTime(),"yyyy-MM-dd HH:mm:ss"));
                }
            }
        }

       *//* if("24".equals(type)){//24小时
            List<String> timelist=new ArrayList<>();
            for (int i = 0; i <24; i++) {//将时间段都放入集合中
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.HOUR_OF_DAY, -i);//i小时后
                timelist.add(df.format(calendar.getTime()));
            }
            *//**//*****************用来查询的时间**********************//**//*
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(date);
            calendar1.add(Calendar.DAY_OF_MONTH, -1);
            calendar1.set(Calendar.MINUTE, 0);
            calendar1.set(Calendar.SECOND, 0);
            calendar1.set(Calendar.MILLISECOND, 0);
            String beginTime=df.format(calendar1.getTime());//24小时前的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR_OF_DAY, 1);//1小时后
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            String endtime=df.format(calendar.getTime());//1小时后的时间
            *//**//*****************用来查询的时间**********************//**//*
            //该时间段 该卡口的所有数据
            List<CllVehicleRecordEntity> clllist=this.list(
                    new QueryWrapper<CllVehicleRecordEntity>()
                            .eq("monitoring_id",monitoringIid)
                            .ge("cross_time",beginTime)
                            .le("cross_time",endtime)
            );
            for (String time1:timelist) {
                int count=0;
                for (CllVehicleRecordEntity cll:clllist) {
                    if(time1.substring(0,14).equals(df.format(cll.getCrossTime()).substring(0,14))){
                        count ++;
                    }
                }
                CllVehicleRecordEntity en=new CllVehicleRecordEntity();
                en.setAreaname(time1.substring(11,13));
                en.setYValie(count);
                list.add(en);
            }
        }else if("30".equals(type)){//30天
            List<String> timelist=new ArrayList<>();
            for (int i = 0; i <30; i++) {//将时间段都放入集合中
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DAY_OF_MONTH, -i);//i天后
                timelist.add(df.format(calendar.getTime()));
            }

            *//**//***********************查询时间***********************************************//**//*
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(date);//用来查询
            calendar1.add(Calendar.DAY_OF_MONTH, -30);
            String beginTime=df1.format(calendar1.getTime())+" 00:00:00";//30天前的时间

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);//用来查询
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String endtime=df1.format(calendar.getTime())+" 00:00:00";//明天 00:00:00
            *//**//***********************查询时间***********************************************//**//*
            //该时间段 该卡口的所有数据
            List<CllVehicleRecordEntity> clllist=this.list(
                    new QueryWrapper<CllVehicleRecordEntity>()
                            .eq("monitoring_id",monitoringIid)
                            .ge("cross_time",beginTime)
                            .le("cross_time",endtime)
            );
            for (String time1:timelist) {
                int count=0;
                for (CllVehicleRecordEntity cll:clllist) {
                    if(time.substring(0,10).equals(df.format(cll.getCrossTime()).substring(0,10))){
                        count ++;
                    }
                }
                CllVehicleRecordEntity en=new CllVehicleRecordEntity();
                en.setAreaname(time1.substring(8,10));
                en.setYValie(count);
                list.add(en);
            }
        }*//*
        Collections.reverse(list);
        return list;
    }*/

    @Override
    public List<CllVehicleRecordEntity> carinout() {
        String area[] = {"京北京","津天津","沪上海","渝重庆","冀河北","豫河南","云云南","辽辽宁","黑黑龙江",
                "湘湖南","皖安徽","鲁山东","新新疆","苏江苏","浙浙江","赣江西","鄂湖北","桂广西","甘甘肃","晋山西",
                "蒙内蒙古","陕陕西","吉吉林","闽福建","贵贵州","粤广东","青青海","藏西藏","川四川","宁宁夏","琼海南"};
        List<CllVehicleRecordEntity> list=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ne("plate_no","无车牌")
                .orderByDesc("cross_time")
                .last("limit 20")
        );
        for (CllVehicleRecordEntity car:list) {
            for (String are:area) {
                if("无车牌".equals(car.getPlateNo())){
                    car.setAreaname("未知");
                }else if(are.substring(0,1).equals(car.getPlateNo().substring(0,1))){
                    car.setAreaname(are.substring(1,are.length()));
                }
            }

        }
        return list;
    }
    @Override
    public List<CllVehicleRecordEntity> cllCartype(String monitoringId, String startTime, String endTime) {

        List<CllVehicleRecordEntity> list=new ArrayList<>();
        List<CllVehicleRecordEntity> grouplist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ge("cross_time",startTime)
                        .le("cross_time",endTime)
                        .eq("monitoring_id",monitoringId)
                        .groupBy("vehicle_type")
        );
        List<CllVehicleRecordEntity> cartypelist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ge("cross_time",startTime)
                        .le("cross_time",endTime)
                        .eq("monitoring_id",monitoringId)
        );
        for (CllVehicleRecordEntity group:grouplist) {
            int count =0;
            for (CllVehicleRecordEntity car:cartypelist) {
                if(car.getVehicleType().equals(group.getVehicleType())){
                    count ++;
                }
            }
            CllVehicleRecordEntity en=new CllVehicleRecordEntity();
            en.setAreaname(group.getVehicleType());
            en.setYValie(count);
            list.add(en);
        }
        return list;
    }
    @Override
    public List<CllVehicleRecordEntity> cartype(String startTime,String endTime) {
        String monitoringId[]={"1bd4530bfe534770a11ea196b34663fc","095852b3f7c948d6b27d5fd698bd1c37"};//进口卡口id
        List<CllVehicleRecordEntity> list=new ArrayList<>();
        List<CllVehicleRecordEntity> grouplist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ge("cross_time",startTime)
                        .le("cross_time",endTime)
                        .in("monitoring_id",Arrays.asList(monitoringId))
                        .groupBy("vehicle_type")
        );
        List<CllVehicleRecordEntity> cartypelist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ge("cross_time",startTime)
                        .le("cross_time",endTime)
                        .in("monitoring_id",Arrays.asList(monitoringId))
        );
        for (CllVehicleRecordEntity group:grouplist) {
            int count =0;
            for (CllVehicleRecordEntity car:cartypelist) {
                if(car.getVehicleType().equals(group.getVehicleType())){
                    count ++;
                }
            }
            CllVehicleRecordEntity en=new CllVehicleRecordEntity();
            en.setAreaname(group.getVehicleType());
            en.setYValie(count);
            list.add(en);
        }
        return list;
    }

    @Override
    public List cllChartday(String monitoringIid, String startTime, String endTime) {
        //查询改时间段内的数据
        List<CllVehicleRecordEntity> RecordList=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .eq("monitoring_id",monitoringIid)
                        .ge("cross_time",startTime)
                        .lt("cross_time",endTime)
                        .orderByAsc("cross_time")
        );
        Long start= DateUtil.parse(startTime).getTime();
        Long end=DateUtil.parse(endTime).getTime();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date(start));
        List<Long> timeList=new ArrayList<>();
        for (Long i = start; i <=end ; i=calendar.getTimeInMillis()) {
            timeList.add(calendar.getTimeInMillis());
            calendar.add(Calendar.DAY_OF_MONTH,1);
        }
        List<String> timeStrList=new ArrayList<>();
        List<Integer> valueList=new ArrayList<>();
        for (Long ltime:timeList) {
            timeStrList.add(DateUtil.format(new Date(ltime),"MM-dd"));
        }
        for (String time:timeStrList) {
            int count=0;
            for (CllVehicleRecordEntity record:RecordList) {
                String tt=DateUtil.format(record.getCrossTime(),"MM-dd");
                if(tt.equals(time)){
                  count ++;
                }
            }
            valueList.add(count);
        }
        List list=new ArrayList();
        list.add(timeStrList);
        list.add(valueList);
        list.add(RecordList.size());

        return list;
    }

    @Override
    public List cllYesterdayTodayThismonth(String startTime, String endTime) {
        List alllist=new ArrayList();
        String monitoringId[]={"1bd4530bfe534770a11ea196b34663fc","095852b3f7c948d6b27d5fd698bd1c37"};
        List<CllVehicleRecordEntity> list=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                .in("monitoring_id", Arrays.asList(monitoringId))
                .le("cross_time",endTime)
                .ge("cross_time",startTime)
        );
        List list1=new ArrayList();
        List list2=new ArrayList();
        for (CllVehicleRecordEntity en:list) {
            if("095852b3f7c948d6b27d5fd698bd1c37".equals(en.getMonitoringId())){//北区
                list2.add(en);
            }else if("1bd4530bfe534770a11ea196b34663fc".equals(en.getMonitoringId())){//南区
                list1.add(en);
            }
        }
        alllist.add(list1);
        alllist.add(list2);
        return alllist;
    }

    @Override
    public List stayTime() {
        String southMonitoringIid ="bdd66d783a974b0a9920890e9958d503";//南区入口id
        String northMonitoringIid ="8827c5b9737648e0911f25cc646034b5";//北区入口id
        String northoutMonitoringIid ="023e9ef9081b46478bb1215949f04dfc";//北区出口id
        String southoutMonitoringIid ="b20934b644394cf19c72f7b7d97c67aa";//南区出口id
        List list=new ArrayList();
        String date=DateUtil.format(new Date(),"yyyy-MM-dd");
        String startTime=date+" 00:00:00";
        String endTime=date+" 23:59:59";
        /*String startTime="2020-05-13 00:00:00";
        String endTime="2020-05-13 23:59:59";*/
        List<CllVehicleRecordEntity> clllist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                .ge("cross_time",startTime)
                .le("cross_time",endTime)
        );
        int scount=0;
        int ncount=0;
        long stayTimes=0L;
        long stayTimen=0L;
        for (CllVehicleRecordEntity cll:clllist) {
            if("1bd4530bfe534770a11ea196b34663fc".equals(cll.getMonitoringId())){//南区入口
                    for (CllVehicleRecordEntity en:clllist) {
                        if("bdc59eaa734e4f2ab048bdaa5e55a6d5".equals(en.getMonitoringId())){//南区出口
                            if(en.getCrossTime().getTime() >cll.getCrossTime().getTime() && en.getPlateNo().equals(cll.getPlateNo())){
                                stayTimes +=(en.getCrossTime().getTime()-cll.getCrossTime().getTime());
                                scount ++;
                            }
                        }
                    }
            }else if("095852b3f7c948d6b27d5fd698bd1c37".equals(cll.getMonitoringId())){//北区入口
                for (CllVehicleRecordEntity en:clllist) {
                    if("695673bb75514da79535e084956b3d76".equals(en.getMonitoringId())){//北区出口
                        if(en.getCrossTime().getTime() >cll.getCrossTime().getTime()  && en.getPlateNo().equals(cll.getPlateNo())){
                            stayTimen +=(en.getCrossTime().getTime() -cll.getCrossTime().getTime());
                            ncount ++;
                        }
                    }
                }
            }
        }
        if(scount ==0){
            scount =1;
        }if(ncount ==0){
            ncount =1;
        }
        long avgs=stayTimes/scount;
        long avgn=stayTimen/ncount;
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 计算差多少天
        //long day = c / nd;
        // 计算差多少小时
        //long hour = c % nd / nh;
        // 计算差多少分钟
        long mins = avgs % nd % nh / nm;
        long minn = avgn % nd % nh / nm;
        long mina = (mins+minn)/2;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        /*System.err.println(day+"天--"+hour+"小时"+min+"分钟");*/
        list.add(mina);
        list.add(mins);
        list.add(minn);
        return list;
    }

    @Override
    public List cllChart(String monitoringIid, String startTime, String endTime) {
        //查询改时间段内的数据
        List<CllVehicleRecordEntity> RecordList=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .eq("monitoring_id",monitoringIid)
                        .ge("cross_time",startTime)
                        .lt("cross_time",endTime)
                        .orderByAsc("cross_time")
        );
        Long start= DateUtil.parse(startTime).getTime();
        Long end=DateUtil.parse(endTime).getTime();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date(start));
        List<Long> timeList=new ArrayList<>();
        for (Long i = start; i <=end ; i=calendar.getTimeInMillis()) {
            calendar.add(Calendar.HOUR,1);
            timeList.add(calendar.getTimeInMillis());
        }
        List<Integer> valueList=new ArrayList<>();
        Long s=start;
        List<String> timeStrList=new ArrayList<>();
        for (int i = 0; i <timeList.size() ; i++) {
            timeStrList.add(DateUtil.format(new Date(timeList.get(i)),"HH:mm"));
            Integer count=0;
            for (CllVehicleRecordEntity record:RecordList) {
                Long crossTime=record.getCrossTime().getTime();
                if(crossTime>=s && crossTime<timeList.get(i)){
                    count++;
                }
            }
            s=timeList.get(i);
            valueList.add(count);
        }
        List list=new ArrayList();
        list.add(timeStrList);
        list.add(valueList);
        list.add(RecordList.size());

        return list;
    }

    @Override
    public List<CllVehicleRecordEntity> carownership(String startTime, String endTime) {
        List<CllVehicleRecordEntity> list=new ArrayList<>();
        String monitoringId[]={"1bd4530bfe534770a11ea196b34663fc","095852b3f7c948d6b27d5fd698bd1c37"};//进口卡口id
        String area[] = {"京北京","津天津","沪上海","渝重庆","冀河北","豫河南","云云南","辽辽宁","黑黑龙江",
                "湘湖南","皖安徽","鲁山东","新新疆","苏江苏","浙浙江","赣江西","鄂湖北","桂广西","甘甘肃","晋山西",
                "蒙内蒙古","陕陕西","吉吉林","闽福建","贵贵州","粤广东","青青海","藏西藏","川四川","宁宁夏","琼海南"};
        //查询该时间段内的所有车辆数据
        List<CllVehicleRecordEntity> carlist=this.list(
                new QueryWrapper<CllVehicleRecordEntity>()
                        .ge("cross_time",startTime)
                        .le("cross_time",endTime)
                        .in("monitoring_id",Arrays.asList(monitoringId))
        );
        for (String are:area) {
            int count=0;
            for (CllVehicleRecordEntity car:carlist) {
                if(car.getPlateNo().substring(0,1).equals(are.substring(0,1))){
                    count ++;
                }
            }
            CllVehicleRecordEntity en=new CllVehicleRecordEntity();
            en.setAreaname(are.substring(0,1));
            en.setYValie(count);
            list.add(en);
        }
        List<CllVehicleRecordEntity> list2=new ArrayList<>();
        for (CllVehicleRecordEntity en:list) {
            if(en.getYValie() != 0){
                list2.add(en);
            }
        }
        //通过销售额 排序
        Collections.sort(list2, new Comparator<CllVehicleRecordEntity>() {
            @Override
            public int compare(CllVehicleRecordEntity o1, CllVehicleRecordEntity o2) {
                int count1= o1.getYValie();
                int count2 = o2.getYValie();
                if(count1<count2){
                    return 1;
                }else if(count1>count2){
                    return -1;
                }else{
                    return 0;
                }
            }
        });
        return list2;
    }
    @Override
    public void illegalEvents(String beginTime, String endTime) throws ParseException {
        Map maps= HikvisionApiUtil.illegalEvents(beginTime,endTime);
        if(maps!=null) {
            Map map = (Map) JSON.parse(maps.get("data").toString());
            JSONArray datas = (JSONArray) JSON.parse(map.get("list").toString());
            List<CllVehicleRecordEntity> recordList = new ArrayList<>();
            List<String> evIdList=new ArrayList<>();
            for(int i = 0;i < datas.size();i++){
                JSONObject job = datas.getJSONObject(i);
                String eventId=job.get("eventId").toString();
                evIdList.add(eventId);
                if(!HikvisionApiUtil.eventIdList.contains(eventId)){
                    CllVehicleRecordEntity record=new CllVehicleRecordEntity();
                    String ct=(job.get("crossTime").toString());
                    Date crossTime=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(ct);
                    record.setCrossTime(crossTime);
                    record.setEventId(eventId);
                    record.setPlateNo(job.get("plateNo").toString());
                    String vehicleType=job.get("vehicleType").toString();
                    vehicleType=HikvisionApiUtil.vehicleTypeMap.get(vehicleType);
                    if(vehicleType==null){
                        vehicleType="轿车";
                    }
                    record.setVehicleType(vehicleType);
                    record.setPlateType(job.get("plateType").toString());
                    record.setMonitoringId(job.get("monitoringId").toString());
                    record.setMonitoringName(job.get("monitoringName").toString());
                    Object platePicUriObj=job.get("platePicUri");
                    if(platePicUriObj!=null){
                        record.setPlatePicUri(platePicUriObj.toString());
                    }
                    Object carPicUriObj=job.get("carPicUri");
                    if(carPicUriObj!=null){
                        record.setCarPicUri(carPicUriObj.toString());
                    }
                    record.setAswSyscode(job.get("aswSyscode").toString());
                    record.setUuid(job.get("uuid").toString());
                    record.setSpeed(job.get("speed").toString());
                    recordList.add(record);
                }
            }
            if(recordList.size()>0){
                this.saveBatch(recordList);
            }
            HikvisionApiUtil.eventIdList=evIdList;
        }
    }

    @Override
    public Integer cllCount(String startTime,String endTime,String monitoringId) {
        Integer count=this.count(new QueryWrapper<CllVehicleRecordEntity>().eq("monitoring_id",monitoringId).ge("cross_time",startTime).le("cross_time",endTime));
        return count;
    }

    @Override
    public List<CllVehicleRecordEntity> cll24hours(String monitoringIid) {
        return null;
    }

}
